import re
import os
import pandas as pd

from function.fun_data_deal import stage_divide
from function.merger import ecg_deal, rrdata_deal
import numpy as np
# 路径设置
from runners_check.data_show import data_show

rri = 'D:\\学习&科研\\华为手表项目\\华为数据\\规律跑者\\check_data\\rri'
detail = 'D:\\学习&科研\\华为手表项目\\华为数据\\规律跑者\\check_data\\detail'
kuaice = 'D:\\学习&科研\\华为手表项目\\华为数据\\规律跑者\\check_data\\kuaice'
fit = 'D:\\学习&科研\\华为手表项目\\华为数据\\规律跑者\\check_data\\fit'
polar = 'D:\\学习&科研\\华为手表项目\\华为数据\\规律跑者'
runner = ['1016','1008','1077']

datetime_pattern = re.compile('\\d{4}-\\d{2}-\\d{2}-\\d{2}时\\d{2}分')


check_csv=[]
check_csv.append(['日期-状态','文件名','polar','华为detail','华为rri','fit数据','健康快测'])

for i in runner:
    # 读取 RRI 数据
    rri_path = os.path.join(rri, f'gl{i}_continuousrri.csv')
    rri_df = pd.read_csv(rri_path)
    rri_filtered_df = rri_df[rri_df['sqi'] == 100].copy()
    rri_filtered_df['timestamp'] = (rri_filtered_df['timestamp'] // 1000).astype(int)

    # 处理 Kuaice 数据
    kuaice_path = os.path.join(kuaice, f'{i}早晚静息.csv')
    kuaice_df = pd.read_csv(kuaice_path)

    # 处理 Fit 数据
    fit_path = os.path.join(fit, f'{i}运动数据.csv')
    fit_df = pd.read_csv(fit_path)

    # 处理 Detail 数据
    detail_path = os.path.join(detail, f'gl{i}_singleworkoutdetail.csv')
    detail_df = pd.read_csv(detail_path)
    detail_df['timestamp'] = (detail_df['timestamp'] // 10 ** 9).astype(int)
    detail_filtered_df = detail_df[['timestamp', '心率']]

    # 获取 Polar 数据
    polar_hr = os.path.join(polar, i, 'rrdata')
    polar_ecg = os.path.join(polar, i, 'data')

    hr_files = os.listdir(polar_hr)
    ecg_files = os.listdir(polar_ecg)

    matched_files = []

    # 匹配文件
    for hr_file in hr_files:
        hr_match = datetime_pattern.search(hr_file)
        if hr_match:
            hr_time = hr_match.group()
            for ecg_file in ecg_files:
                ecg_match = datetime_pattern.search(ecg_file)
                if ecg_match and ecg_match.group() == hr_time:
                    matched_files.append((hr_file, ecg_file))

    # 处理匹配的文件
    for hr_file, ecg_file in matched_files:
        
        print('匹配的文件',hr_file, ecg_file)
        hr_file_path = os.path.join(polar_hr, hr_file)
        ecg_file_path = os.path.join(polar_ecg, ecg_file)
        hr_file_size = os.path.getsize(hr_file_path)
        ecg_file_size = os.path.getsize(ecg_file_path)
        min_size_kb=1*1024
        if hr_file_size >= min_size_kb and ecg_file_size >= min_size_kb:
        

            ecg_df = ecg_deal(ecg_file_path)
            hr_df = rrdata_deal(hr_file_path)
            if len(ecg_df)<50 and len(hr_df)<=5 and len(ecg_df)<20:
                continue
            stage_list = []
            
            all_start=int(ecg_df.iloc[0]['ecg_timestamp'])//1000
            all_end=int(ecg_df.iloc[-1]['ecg_timestamp'])//1000
            all_stage=[1,all_start,all_end]
            for stage in [1, 2, 3, 4]:
                stage_df = ecg_df[ecg_df['stage'] == str(stage)]
                if len(stage_df) > 2:
                    first_timestamp = int(stage_df.iloc[0]['ecg_timestamp'])//1000
                    last_timestamp = int(stage_df.iloc[-1]['ecg_timestamp'])//1000
                    stage_list.append([stage, first_timestamp, last_timestamp])
                    # print(f"Stage {stage} 满足条件，添加到列表中")

            # 处理数据统一,  stage_list,rri_filtered_df,kuaice_df,fit_df,detail_filtered_df,hr_df
            # print(hr_file,stage_list)

            # 假设 stage_list 的格式为 [[stage, start_timestamp, end_timestamp], ...]
            # 示例 stage_list
            # stage_list = [[1, 1700000000, 1700003600], [2, 1700010000, 1700013600], ...]

            # 创建一个字典来存储符合条件的数据

            filtered_data = {
                '华为rri': [],
                '健康快测': [],
                'fit文件': [],
                '运动详情': []
            }

            # 遍历 stage_list

            stage, start_timestamp, end_timestamp = all_stage


            # 确保时间戳为整型
            start_timestamp = int(start_timestamp)
            end_timestamp = int(end_timestamp)

            # 从 rri_filtered_df 中筛选数据

            rri_stage_data = rri_filtered_df[(rri_filtered_df['timestamp'] >= start_timestamp) &
                                            (rri_filtered_df['timestamp'] <= end_timestamp)]
            # 确保 timestamp 列为 datetime64 类型
            rri_stage_data.loc[:,'timestamp'] = pd.to_datetime(rri_stage_data['timestamp'], unit='s', errors='coerce')
            filtered_data['华为rri'].append(rri_stage_data)

            # 从 kuaice_df 中筛选数据
            kuaice_stage_data = kuaice_df[(kuaice_df['timestamp'] >= start_timestamp-100) &
                                        (kuaice_df['timestamp'] <= end_timestamp+100)]
            # 确保 timestamp 列为 datetime64 类型
            kuaice_stage_data.loc[:,'timestamp'] = pd.to_datetime(kuaice_stage_data['timestamp'], unit='s', errors='coerce')
            filtered_data['健康快测'].append(kuaice_stage_data)

            # 从 fit_df 中筛选数据
            fit_stage_data = fit_df[(fit_df['timestamp'] >= start_timestamp) &
                                    (fit_df['timestamp'] <= end_timestamp)]
            # 确保 timestamp 列为 datetime64 类型
            fit_stage_data.loc[:,'timestamp'] = pd.to_datetime(fit_stage_data['timestamp'], unit='s', errors='coerce')
            filtered_data['fit文件'].append(fit_stage_data)


            # 从 detail_filtered_df 中筛选数据
            detail_stage_data = detail_filtered_df[(detail_filtered_df['timestamp'] >= start_timestamp) &
                                                (detail_filtered_df['timestamp'] <= end_timestamp)]
            # 确保 timestamp 列为 datetime64 类型
            detail_stage_data.loc[:,'timestamp'] = pd.to_datetime(detail_stage_data['timestamp'], unit='s', errors='coerce')
            detail_stage_data.loc[:,'心率']=detail_stage_data['心率'].astype('int64')
            filtered_data['运动详情'].append(detail_stage_data)

            # 将字符串类型的 13 位时间戳转换为整数，并转换为 10 位时间戳
            hr_df['timestamp'] = hr_df['timestamp'].astype('int64')

            # 将时间戳从毫秒转换为秒
            hr_df['timestamp'] = hr_df['timestamp'] // 1000
            hr_df['timestamp']=pd.to_datetime(hr_df['timestamp'], unit='s', errors='coerce')
            hr_df['rr1']=hr_df['rr1'].astype('int64')
            hr_df['HR']=hr_df['HR'].astype('int64')

            # 输出筛选后的数据
            # 输出筛选后的数据及其长度
            # 输出筛选后的数据及其长度
            # for cla, data in filtered_data.items():
            #     print(f"数据类型 {cla}，数据长度 ：{len(data[0])}",data[0].head())
            #
            # print(hr_df.columns,'----',rri_stage_data.columns,'-----',kuaice_df.columns,'-----',fit_stage_data.columns,'-----',detail_stage_data.columns)

        
            check_list=data_show(hr_file,stage_list,hr_df,detail_df=filtered_data['运动详情'][0],rri_df=filtered_data['华为rri'][0],fit_df=filtered_data['fit文件'][0],kuaice_df=filtered_data['健康快测'][0])
            
            print(check_list)
            check_csv.append(check_list)

check_df=pd.DataFrame(check_csv[1:], columns=check_csv[0])  # 使用第一行作为列名
print(check_df)
check_df.to_csv(f'D:\\学习&科研\\华为手表项目\\华为数据\\规律跑者\\check_data\\check_result.csv')
